package priv.zgh.forum.re.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import priv.zgh.forum.auth.entity.Role;
import priv.zgh.forum.exception.ForumException;
import priv.zgh.forum.re.entity.ResourcesSimulator;
import priv.zgh.forum.re.service.ResourcesSimulatorService;
import priv.zgh.forum.utils.R;
import priv.zgh.forum.utils.RandomUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZGH
 * @since 2022-04-21
 */
@CrossOrigin
@RestController
@RequestMapping("/resources/simulator")
public class ResourcesSimulatorController {
    ResourcesSimulatorService resourcesSimulatorService;
    @Autowired
    public void setResourcesSimulatorService(ResourcesSimulatorService resourcesSimulatorService) {
        this.resourcesSimulatorService = resourcesSimulatorService;
    }

    @ApiOperation(value = "按照传入条件来进行分页查询模拟器资源.")
    @PostMapping(path = "pageSimulatorResourcesCondition/{current}/{limit}")
    public R pageTeacherCondition(@PathVariable long current, @PathVariable long limit, @RequestBody(required = false) ResourcesSimulator query){
        Page<ResourcesSimulator> page = resourcesSimulatorService.pageResourcesConditionByType(0,current,limit,query);
        return R.ok().data("total",page.getTotal()).data("rows",page.getRecords());
    }

    @ApiOperation(value = "根据ID来获取模拟器信息.")
    @GetMapping(path = "/getResourcesSimulator/{id}")
    public R getResourcesSimulatorById(@PathVariable String id){
        ResourcesSimulator simulator = resourcesSimulatorService.getById(id);
        return R.ok().data("simulator",simulator);
    }

    @ApiOperation(value = "按照传入ID删除模拟器.")
    @DeleteMapping(path = "/delete/{id}")
    public R remoteTeacher(@ApiParam(name = "id",value = "模拟器ID",required = true) @PathVariable(name = "id") String id){
        boolean flush = resourcesSimulatorService.removeById(id);
        if(flush){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @ApiOperation("模拟器上传")
    @PostMapping("/upload")
    public R updateGame(@RequestPart(name = "file",required = false) MultipartFile file, @RequestPart(name = "files",required = false) MultipartFile[] files) throws IOException {
        boolean isReceive = false;
        String saveFileName = "";
        List<String> saveFileNameList = new ArrayList<>();
        if(file != null){
            isReceive = true;
            //获取上传时的文件名(包括扩展名),就是文件的名称
            String originalFileName = file.getOriginalFilename();
            String[] splitOriginalFilename = originalFileName.split("\\.");
            saveFileName = splitOriginalFilename[0] + '_' + RandomUtil.getSixBitRandom() + '.' + splitOriginalFilename[1];
            //调用次方法就可以直接保存到指定的文件夹下
            file.transferTo(new File("E:\\怀旧游戏交流分享社区文件\\模拟器\\" + saveFileName));
        }
        if(files != null && files.length != 0){

            isReceive = true;
            for(MultipartFile item:files){
                String originalFilename = item.getOriginalFilename();
                String[] splitOriginalFilename = StringUtils.split("\\.",originalFilename);
                String temp = splitOriginalFilename[0] + '_' + RandomUtil.getSixBitRandom() + '.' + splitOriginalFilename[1];
                item.transferTo(new File("E:\\怀旧游戏交流分享社区文件\\模拟器\\" + temp));
                saveFileNameList.add(temp);
            }
        }
        if(!isReceive){
            return R.error().message("接收文件为空!");
        }
        return R.ok().message("上传成功!").data("fileName",saveFileName).data("fileNameList",saveFileNameList);
    }

    @ApiOperation(value = "保存模拟器信息.")
    @PostMapping(path = "/addResourcesSimulator")
    public R addTeacher(@RequestBody ResourcesSimulator simulator){
        // 设置基本信息
        simulator.setUpdateTime(new Date());
        boolean save = resourcesSimulatorService.save(simulator);
        if(save){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @ApiOperation("模拟器资源下载")
    @GetMapping("/download/{id}")
    public String downloadFile( @PathVariable(name = "id") String id,HttpServletResponse response) {
        String fileName = resourcesSimulatorService.getById(id).getFileName();// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File("E:\\怀旧游戏交流分享社区文件\\模拟器\\" + fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }else{
                throw new ForumException(20001,"后端此文件不存在!");
            }
        }
        return "下载失败";
    }

    @ApiOperation(value = "更新此ID的模拟器信息.")
    @PostMapping(path = "/updateSimulator")
    public R updateTeacher(@RequestBody ResourcesSimulator simulator){
        boolean flush = resourcesSimulatorService.updateById(simulator);
        if(flush){
            return R.ok();
        }else{
            return R.error();
        }
    }
}

